package com.changeover.handler;

import static com.google.common.base.Preconditions.checkArgument;
import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.changeover.gwt.shared.action.LoginAction;
import com.changeover.gwt.shared.result.LoginResult;
import com.changeover.gwt.shared.validation.LoginFieldVerifier;
import com.changeover.service.IUserService;

/**
 * Server handler for login action
 * 
 * @author Roman Kostenko
 */
@Service
public class LoginHandler implements ActionHandler<LoginAction, LoginResult> {

    @Autowired
    private IUserService userService;

    public Class<LoginAction> getActionType() {
        return LoginAction.class;
    }

    public synchronized LoginResult execute(LoginAction action, ExecutionContext context)
        throws ActionException {
        // Escape data from the client to avoid cross-site script vulnerabilities.
        String login = escapeHtml(action.getLoginInfo().getLogin());
        String password = escapeHtml(action.getLoginInfo().getPassword());

        // Verify that the input is valid.
        // If the input is not valid, throw an IllegalArgumentException back to
        // the client.
        checkArgument(LoginFieldVerifier.isValidLogin(login), "Login must be at least 4 characters long");
        checkArgument(LoginFieldVerifier.isValidPassword(password),
            "Password must be at least 6 characters long");

        // Authorization checks

        // Authorization

        return new LoginResult("OK");
    }

    public synchronized void rollback(LoginAction action, LoginResult result, ExecutionContext context)
        throws ActionException {
        // Reset to the previous value.
    }

    /**
     * Escape an html string. Escaping data received from the client helps to prevent cross-site
     * script vulnerabilities.
     * 
     * @param html the html string to escape
     * @return the escaped string
     */
    private String escapeHtml(String html) {
        if (html == null) {
            return null;
        }
        return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    }
}
